<template>
  <div class="community-container" :class="{ mobile: settingStore.isMobile }">
    <!-- 顶部横幅 -->
    <div class="community-banner">
      <div class="banner-content">
        <h1 class="banner-title">开发者社区</h1>
        <p class="banner-subtitle">与千万开发者共同成长，分享技术，交流经验</p>
        <div class="banner-stats">
          <div class="stat-item">
            <span class="stat-number">{{ (statistics.totalPosts || 0).toLocaleString() }}</span>
            <span class="stat-label">技术文章</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ (statistics.totalUsers || 0).toLocaleString() }}</span>
            <span class="stat-label">开发者</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ formatViews(statistics.totalViews || 0) }}</span>
            <span class="stat-label">总浏览量</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="container mx-auto max-w-screen-xl">
      <!-- 搜索和筛选区域 -->
      <div class="community-toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索感兴趣的内容..."
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" @click="handlePublish">
            <el-icon class="mr-1"><Edit /></el-icon>
            发布文章
          </el-button>
        </div>
      </div>

      <!-- 分类标签 - 暂时隐藏 -->
      <!-- <div class="category-tabs">
        <el-tag
          v-for="category in categories"
          :key="category.value"
          :type="selectedCategory === category.value ? 'primary' : 'info'"
          :effect="selectedCategory === category.value ? 'dark' : 'plain'"
          @click="selectCategory(category.value)"
          class="category-tag"
          size="large"
        >
          {{ category.label }}
        </el-tag>
      </div> -->

      <!-- 排序选项 -->
      <div class="sort-tabs">
        <el-radio-group v-model="sortType" @change="handleSortChange">
          <el-radio-button label="latest">最新发布</el-radio-button>
          <el-radio-button label="hot">最热文章</el-radio-button>
          <el-radio-button label="recommend">推荐内容</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 社区列表 -->
      <div v-loading="loading" class="community-list">
        <CommunityCard
          @click="toDetail(item._id)"
          v-for="item in communityData"
          :key="item._id"
          :data="item"
        />
      </div>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && communityData.length === 0"
        description="暂无内容，快来发布第一篇文章吧！"
        :image-size="200"
      >
        <el-button type="primary" @click="handlePublish">立即发布</el-button>
      </el-empty>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pageData.total > 0">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="pageData.total"
          v-model:page-size="pageData.pageSize"
          v-model:current-page="pageData.page"
          @current-change="changePage"
          @size-change="changePageSize"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import CommunityCard from "./components/CommunityCard.vue"
import { ref, onMounted } from "vue"
import { Search, Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getCommunityListAPI, getCommunityStatisticsAPI, getCommunityCategoriesAPI } from "@/api/web/community"
import type { CommunityItem } from "@/types/web/community"
import { useRouter } from "vue-router"
import { useSettingsStore } from "@/store/modules/settings"

const settingStore = useSettingsStore()
// 全局路由
const router = useRouter()

// 分页数据
const pageData = ref({
  page: 1,
  pageSize: 9,
  total: 0
})

// 社区数据
const communityData = ref<CommunityItem[]>([])

// 搜索关键词
const searchKeyword = ref('')

// 选中的分类
const selectedCategory = ref('all')

// 排序类型
const sortType = ref('latest')

// 统计数据
const statistics = ref({
  totalPosts: 0,
  totalUsers: 0,
  totalViews: 0
})

// 分类列表
const categories = ref([
  { label: '全部', value: 'all' },
  { label: '技术分享', value: 'tech' },
  { label: '项目实战', value: 'project' },
  { label: '前端开发', value: 'frontend' },
  { label: '后端开发', value: 'backend' },
  { label: '移动开发', value: 'mobile' },
  { label: '人工智能', value: 'ai' },
  { label: '架构设计', value: 'architecture' }
])

// 使用 map 方法提取 tags 中的 name 字段
const extractTagNames = (tags: any[]) => {
  // 方法1：直接使用 map 提取 name
  const tagNames = tags.map(tag => tag.name)
  console.log('提取的标签名称:', tagNames)
  return tagNames
}

// 使用 map 方法提取 tags 中的 name 字段（带过滤）
const extractTagNamesWithFilter = (tags: any[]) => {
  // 方法2：使用 map 提取 name 并过滤空值
  const tagNames = tags
    .map(tag => tag.name)
    .filter(name => name && name.trim() !== '')
  console.log('过滤后的标签名称:', tagNames)
  return tagNames
}

// 使用 map 方法提取 tags 中的 name 字段（去重）
const extractUniqueTagNames = (tags: any[]) => {
  // 方法3：使用 map 提取 name 并去重
  const uniqueTagNames = [...new Set(tags.map(tag => tag.name))]
  console.log('去重后的标签名称:', uniqueTagNames)
  return uniqueTagNames
}

// 分页数据改变
const changePage = (page: number) => {
  pageData.value.page = page
  getCommunityList()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const changePageSize = (pageSize: number) => {
  pageData.value.pageSize = pageSize
  pageData.value.page = 1
  getCommunityList()
}

// 加载
const loading = ref(false)

// 格式化浏览量显示
const formatViews = (views: number) => {
  if (views >= 10000) {
    return `${(views / 10000).toFixed(1)}万+`
  }
  return views.toLocaleString()
}

// 获取社区列表
const getCommunityList = async () => {
  loading.value = true
  try {
    const res = await getCommunityListAPI(pageData.value.page, pageData.value.pageSize, {
      keyword: searchKeyword.value,
      category: selectedCategory.value === 'all' ? undefined : selectedCategory.value,
      sort: sortType.value
    })
    // 直接使用 res.data 处理数据
    if (res.data) {
      communityData.value = (res as any).data || []

      // 示例：使用 map 方法提取所有文章的标签名称
      if (communityData.value && Array.isArray(communityData.value)) {
        const allTags = communityData.value.flatMap((item: any) => item.tags || [])
        const allTagNames = extractTagNames(allTags)
        console.log('所有文章的标签名称:', allTagNames)

        // 示例：提取去重后的标签名称
        const uniqueTagNames = extractUniqueTagNames(allTags)
        console.log('去重后的标签名称:', uniqueTagNames)

        // 示例：根据你的数据格式，tags 数组中每个对象都有 name 字段
        // 例如：tags: [{ _id: "683056947d1cb2263c479fd3", name: "ElementUI" }, ...]
        console.log('标签对象示例:', allTags.slice(0, 2)) // 显示前两个标签对象
      }

      pageData.value.total = (res as any).total || 0
    }
  } catch (error) {
    ElMessage.error('获取社区列表失败')
    console.error('获取社区列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 点击跳转至详情页
const toDetail = (id?: string) => {
  router.push(`/home-detail?id=${id}&type=community`)
}

// 选择分类 - 暂时注释
// const selectCategory = (category: string) => {
//   selectedCategory.value = category
//   pageData.value.page = 1
//   getCommunityList()
// }

// 排序改变
const handleSortChange = () => {
  pageData.value.page = 1
  getCommunityList()
}

// 搜索
const handleSearch = () => {
  pageData.value.page = 1
  getCommunityList()
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getCommunityStatisticsAPI()
    if (res.data) {
      statistics.value = {
        totalPosts: (res as any).data?.totalPosts || 0,
        totalUsers: (res as any).data?.totalUsers || 0,
        totalViews: (res as any).data?.totalViews || 0
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await getCommunityCategoriesAPI()
    if (res.data) {
      // 将后端返回的分类数据转换为前端需要的格式
      const backendCategories = ((res as any).data || []).map((item: any) => ({
        label: item.name,
        value: item.slug
      }))
      categories.value = [
        { label: '全部', value: 'all' },
        ...backendCategories
      ]
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 发布文章
const handlePublish = () => {
  // 跳转到后台文章发布页面
  router.push('/article-add')
}

onMounted(async () => {
  await Promise.all([
    getStatistics(),
    // getCategories(), // 暂时注释掉分类获取
    getCommunityList()
  ])
})
</script>

<style scoped lang="scss">
.community-container {
  min-height: 100vh;
  background: #f5f7fa;
}

// 顶部横幅
.community-banner {
  background: var(--gradient-primary);
  padding: 60px 20px;
  color: white;
  text-align: center;

  .banner-content {
    max-width: 1200px;
    margin: 0 auto;
  }

  .banner-title {
    font-size: 42px;
    font-weight: bold;
    margin-bottom: 15px;
    text-shadow: 0 2px 4px rgba(0,0,0,0.2);
  }

  .banner-subtitle {
    font-size: 18px;
    margin-bottom: 30px;
    opacity: 0.95;
  }

  .banner-stats {
    display: flex;
    justify-content: center;
    gap: 60px;
    margin-top: 40px;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .stat-number {
        font-size: 32px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
}

// 工具栏
.community-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px 0 20px;
  gap: 20px;

  .toolbar-left {
    flex: 1;
    max-width: 600px;
  }

  .search-input {
    width: 100%;

    :deep(.el-input__wrapper) {
      border-radius: 20px;
      padding: 8px 20px;
    }
  }

  .toolbar-right {
    display: flex;
    gap: 10px;

    .el-button {
      border-radius: 20px;
      padding: 10px 25px;
    }
  }
}

// 分类标签
.category-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 20px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 20px;

  .category-tag {
    cursor: pointer;
    transition: all 0.3s;
    border-radius: 20px;
    padding: 8px 20px;
    font-size: 14px;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
  }
}

// 排序选项
.sort-tabs {
  padding: 15px 0;

  :deep(.el-radio-button__inner) {
    border-radius: 0;
    border-left: 1px solid #dcdfe6;

    &:first-child {
      border-radius: 4px 0 0 4px;
    }

    &:last-child {
      border-radius: 0 4px 4px 0;
    }
  }
}

// 社区列表
.community-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 20px 0;
  min-height: 400px;
}

// 分页
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

// 移动端适配
.mobile {
  .community-banner {
    padding: 40px 15px;

    .banner-title {
      font-size: 28px;
    }

    .banner-subtitle {
      font-size: 14px;
    }

    .banner-stats {
      gap: 30px;

      .stat-item {
        .stat-number {
          font-size: 24px;
        }

        .stat-label {
          font-size: 12px;
        }
      }
    }
  }

  .community-toolbar {
    flex-direction: column;
    padding: 20px 0;

    .toolbar-left,
    .toolbar-right {
      width: 100%;
    }
  }

  .category-tabs {
    gap: 8px;

    .category-tag {
      font-size: 12px;
      padding: 6px 15px;
    }
  }

  .community-list {
    grid-template-columns: 1fr;
    gap: 15px;
  }
}

// 中等屏幕（平板）
@media (max-width: 1024px) {
  .community-list {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>

